package com.pro01.apirednote.service.serviceImpl;

import com.pro01.apirednote.dto.CommentRequest;
import com.pro01.apirednote.dto.CommentResponse;
import com.pro01.apirednote.mapper.CommentMapper;
import com.pro01.apirednote.mapper.ContentMapper;
import com.pro01.apirednote.pojo.Comment;
import com.pro01.apirednote.pojo.Result;
import com.pro01.apirednote.pojo.PageResult;
import com.pro01.apirednote.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final CommentMapper commentMapper;

    private final ContentMapper contentMapper;


    // 用户发布评论
    @Override
    public Result<?> addComment(Long userId, Long contentId, CommentRequest request) {
        Comment comment = new Comment();
        comment.setContentId(contentId);
        comment.setUserId(userId);
        comment.setParentId(request.getParentId());
        comment.setText(request.getText());
        commentMapper.insertComment(comment);

        // ⭐ 评论数 +1
        contentMapper.incrementCommentCount(contentId);

        return Result.success();
    }

    // 用户查看评论列表
    @Override
    public Result<PageResult<CommentResponse>> getCommentsByContent(Long contentId, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<CommentResponse> records = commentMapper.getCommentsByContentId(contentId, offset, pageSize);
        Long total = commentMapper.countCommentsByContentId(contentId);
        return Result.success(PageResult.of(total, records));
    }

    // 删除评论
    @Override
    public Result<Void> deleteComment(Long commentId, Long userId, String role) {
        boolean isAdmin = "ADMIN".equalsIgnoreCase(role);

        // ① 先查出评论对应的 contentId
        Long contentId = commentMapper.findContentIdByCommentId(commentId);
        if (contentId == null) {
            return Result.error("评论不存在");
        }

        // ② 执行删除操作
        int rows = commentMapper.deleteCommentById(commentId, userId, isAdmin);

        // ③ 删除成功后，评论数 -1
        if (rows > 0) {
            contentMapper.decrementCommentCount(contentId); // 👈 新增逻辑
            return Result.success();
        } else {
            return Result.error("无权限删除该评论");
        }
    }
    
}